
import os,sys

from PyQt6.QtWidgets import QMainWindow,QApplication
from PyQt6.QtGui import QImage,QPixmap
from PyQt6.QtCore import pyqtSlot,pyqtSignal
from ArgumentSettings_UI import Ui_ArgumentSettingsWindow
import numpy as np
from typing import List,AnyStr,Callable

import cv2 as cv

class ArgumentSettingWindow(QMainWindow):
    imageUpdateSignal = pyqtSignal(str,np.ndarray,name='imageUpdateSignal')
    def __init__(self, 
                 parent=None,
                 arguments: List[AnyStr] = [],
                 previews:  List[AnyStr] = [],
                 argumentUpdateCallback: Callable = lambda x:None,
                 saveArgumentsCallback: Callable = lambda:None
                 ):
        super().__init__(parent)
        self.previews = previews
        self.arguments = arguments
        self.previewIndex = 0
        self.argumentIndex = 0
        self.argumentsDict = {}
        
        for key in arguments:
            self.argumentsDict[key] = 0
        
        self.ui = Ui_ArgumentSettingsWindow()
        self.ui.setupUi(self)
        self.ui.argumentComboBox.addItems(arguments)
        self.ui.previewComboBox.addItems(previews)
        self.argumentUpdateCallback = argumentUpdateCallback
        self.saveArgumentsCallback = saveArgumentsCallback
        self.imageUpdateSignal.connect(self.updateImageView)    
    def setArguments(self,kvPairs: dict):
        for key in list(kvPairs.keys()):
            self.argumentsDict[key] = kvPairs[key]
    
    def getArguments(self):
        return self.arguments
    
    def getPreviewName(self):
        return self.previews[self.previewIndex]
    
    @pyqtSlot(int)
    def on_previewComboBox_currentIndexChanged(self, index: int):
        self.previewIndex = index
    
    @pyqtSlot(int)
    def on_argumentComboBox_currentIndexChanged(self, index: int):
        self.argumentIndex = index
        argument = self.arguments[index]
        value = self.argumentsDict[argument]
        self.ui.argumentAdjustSlider.setValue(value)
        self.ui.argumentValueBox.setPlainText(str(value))
    
    @pyqtSlot(int)
    def on_argumentAdjustSlider_valueChanged(self, value: int):
        self.ui.argumentValueBox.setPlainText(str(value))
        argumentIndex = self.ui.argumentComboBox.currentIndex()
        argument = self.arguments[argumentIndex]
        self.argumentsDict[argument] = value
        self.argumentUpdateCallback(self.argumentsDict)
    
    @pyqtSlot(str, np.ndarray)
    def updateImageView(self, name:str, image: np.ndarray):
        if self.previews[self.previewIndex] == name:
            image = image.copy()
            image = cv.cvtColor(image,cv.COLOR_BGR2RGB)
            qim = QImage(image.data,image.shape[1],image.shape[0],QImage.Format.Format_RGB888)
            qpx = QPixmap.fromImage(qim)
            self.ui.ImageView.setPixmap(qpx)
    @pyqtSlot()
    def on_saveButton_pressed(self):
        self.saveArgumentsCallback()
    